<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryApiBook } from '@/api/books'
import { borrowApiBook } from '@/api/borrowbook'

//钩子函数 --自动刷新界面
onMounted(() => {
    onSubmit()
})

//搜索栏对象
const searchBook = ref({ ISBN: '', category: '', date: [], begin: '', end: '' })

//表格渲染数据
const bookList = ref([])

//借阅图书基本数据
const userData = ref({
    id: '',
    username: '',
    name: '',
    bookNum: '',
})

//添加watch侦听
watch(() => searchBook.value.date, (newVal, oldVal) => {
    if (newVal && newVal.length == 2) {
        searchBook.value.begin = newVal[0]
        searchBook.value.end = newVal[1]
    }
})

//查询按钮
const onSubmit = async () => {
    const reuslt = await queryApiBook(searchBook.value.ISBN, searchBook.value.category, searchBook.value.begin, searchBook.value.end, currentPage.value, pageSize.value)
    if (reuslt && typeof reuslt === 'object') {
        const data = reuslt.data || reuslt
        bookList.value = data.records || []
        total.value = data.total || 0
    } else {
        ElMessage.error("查询失败")
    }
}

// 初始页码
const currentPage = ref(1)
// 每页记录数
const pageSize = ref(10)
const background = ref(true)
const disabled = ref(false)
const total = ref(0) // 页码总记录数

const handleSizeChange = () => {
    pageSize.value = val;
    onSubmit()
}
const handleCurrentChange = () => {
    currentPage.value = val;
    onSubmit()
}
const handleSelectionChange = (val) => { 
    userData.value.bookNum = val.length
    onSubmit()
}
//保存借书用户数据
const save = async () => {
    try{
const result = await borrowApiBook(userData.value)
    if (result && result.code === 1) {
        ElMessage.success("借阅成功")
        onSubmit()
        dialogVisible.value = false;
    } else {
        ElMessage.error("请检查用户名或者姓名" || result?.msg)
    }
    }catch(err){
        ElMessage.error("网络错误，请稍后重试")
    }
    
}

// 添加图书
const dialogVisible = ref(false)

// 弹窗标题
const dialogTitle = ref('添加图书')

//添加借书确认按钮
const borrowBtn =  (row) => {
    //检查图书数量是否为0
    if(row.bookNum <= 0){
        ElMessage.error('该图书库存为0，无法借阅')
        return
    }
    dialogVisible.value = true
    dialogTitle.value = '添加借阅用户'
    userData.value.id = row.id


    //重置表单的校验规则 --提示信息
    if (UserFromRef.value) {
        UserFromRef.value.resetFields();
    }
}

const rules = ref({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '姓名不能为空', trigger: 'blur' },
        { min: 2, max: 12, message: '姓名长度在2到12个字', trigger: 'bulr' }
    ],
    bookNum: [
        { required: true, message: '借阅数量至少一本', trigger: 'blur' },
        { min: 1, max: 3, message: '最大可借阅3本图书', trigger: 'blur' }
    ]
})

//校验对象
const UserFromRef = ref()
</script>

<template>
    <h2>图书借阅</h2>
    <!-- 搜素栏 -->
    <div class="container">
        {{ searchBook }}
        <el-form :inline="true" :model="searchBook" class="demo-form-inline">
            <!-- 根据ISBN查询 -->
            <el-form-item label="ISBN:">
                <el-input v-model="searchBook.ISBN" placeholder="请输入ISBN号" clearable />
            </el-form-item>

            <!-- 根据分类查询 -->
            <el-form-item label="分类:">
                <el-select v-model="searchBook.category" placeholder="请选择分类" clearable>
                    <el-option label="科幻书籍" value="1" />
                    <el-option label="动漫小说" value="2" />
                    <el-option label="单词大典" value="3" />
                    <el-option label="传统经典" value="4" />
                    <el-option label="军事类" value="5" />
                    <el-option label="天文类" value="6" />
                    <el-option label="生活类" value="7" />
                    <el-option label="其他" value="0" />
                </el-select>
            </el-form-item>

            <!-- 根据时间查询 -->
            <el-form-item label="时间范围:">
                <el-date-picker v-model="searchBook.date" type="daterange" range-separator="到" start-placeholder="开始时间"
                    end-placeholder="结束时间" value-format="YYYY-MM-DD" />
                <!--         searchEmp.date:绑定数据   daterange：时间范围属性  range-separator：设置中间的分割字样 start-placeholder：开始时间的提示语 end-placeholder：结束时间的提示语                                                                                                                                              -->
            </el-form-item>

            <!-- 查询和删除 -->
            <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
                <el-button type="info" @click="remove">清除</el-button>
            </el-form-item>
        </el-form>
    </div>

    <!-- 表格 -->
    <div class="container">
        <el-table :data="bookList" border style="width: 100%" @selection-change="handleSelectionChange">
            <!-- 勾选复选框 -->
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="title" label="书名" width="100" />
            <el-table-column label="图片" width="120" align="center">
                <template #default="scope">
                    <img :src="scope.row.image" height="40px">
                </template>
            </el-table-column>
            <el-table-column prop="author" label="作者" width="120" />
            <el-table-column prop="ISBN" label="ISBN" width="120" />
            <el-table-column prop="category" label="图书分类" width="180">
                <template #default="scope">
                    <span v-if="scope.row.category == 1">科幻小说</span>
                    <span v-else-if="scope.row.category == 2">动漫小说</span>
                    <span v-else-if="scope.row.category == 3">单词大典</span>
                    <span v-else-if="scope.row.category == 4">传统经典</span>
                    <span v-else-if="scope.row.category == 5">军事类</span>
                    <span v-else-if="scope.row.category == 6">天文类</span>
                    <span v-else-if="scope.row.category == 7">生活类</span>
                    <span v-else="scope.row.category == 0">其他</span>
                </template>
            </el-table-column>
            <el-table-column prop="bookNum" label="数量" width="105" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="borrowBtn(scope.row)" :disabled="scope.row.bookNum <= 0" >
                        借书
                    </el-button> 
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 分页条 -->
    <div class="container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30, 40]"
            :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>


    <!-- 借阅图书 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500" center>
        {{ userData }}
        <el-form :model="userData" label-width="auto" style="max-width: 600px" :rules="rules" ref="UserFromRef">
            <el-form-item label="用户名:" prop="username">
                <el-input v-model="userData.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="姓名:" prop="name">
                <el-input v-model="userData.name" placeholder="请输入借阅者的姓名" />
            </el-form-item>
            <el-form-item label="借阅数量:" prop="bookNum">
                <el-input v-model="userData.bookNum" placeholder="请输入借阅数量" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="save">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>

</template>

<style>
.container {
    margin: 15px 0px;
}
</style>